//
//  NYADDTagViewController.m
//  百思不得姐
//
//  Created by Apple on 15/8/22.
//  Copyright (c) 2015年 Neal. All rights reserved.
//

#import "NYADDTagViewController.h"
#import "NYTagsButton.h"
#import "NYTagTextField.h"
#import <SVProgressHUD.h>
@interface NYADDTagViewController ()<UITextFieldDelegate>
/* 内容控件 */
@property(nonatomic , weak) UIView *contentView;
/* 文本输入框 */
@property(nonatomic , weak) UITextField *tagTextField;
/* 添加标签按钮 */
@property(nonatomic , weak) UIButton *addTagButton;
/* tagsbuttons */
@property(nonatomic , strong) NSMutableArray *tagButtons;

@end

@implementation NYADDTagViewController
#pragma mark - 懒加载
- (NSMutableArray *)tagButtons
{
    if (_tagButtons == nil) {
        _tagButtons = [NSMutableArray array];
    }
    return _tagButtons;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = NYGlobalBg;
    [self setupNav];
    [self setupContentView];
    [self setupTextField];
    [self setupTagButtons];
}

#pragma mark - 初始化导航条
- (void)setupNav
{
    self.navigationItem.title = @"添加标签";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style: UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style: UIBarButtonItemStyleDone target:self action:@selector(finish)];
    [self.navigationController.navigationBar layoutIfNeeded];
    
}
- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)finish
{
    /**
     *  传递标签数据，代理，通知，block
     */
    NSArray *tags = [_tagButtons valueForKeyPath:@"currentTitle"];
    
    !self.tagblock? : self.tagblock(tags);
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 设置内容
- (void)setupContentView
{
    UIView *contentView = [[UIView alloc]init];
    contentView.backgroundColor = [UIColor whiteColor];
    contentView.x = SmallMargin;
    contentView.y =64;
    contentView.width = self.view.width- 2 * SmallMargin;
    contentView.height = self.view.height;
    [self.view addSubview:contentView];
    self.contentView = contentView;
}
- (void)setupTextField
{
    NYTagTextField *textfield = [[NYTagTextField alloc]init];
    [self.contentView addSubview:textfield];
    self.tagTextField = textfield;
    NYWeakSelf;
    textfield.width = self.contentView.width;
    textfield.height = NYtagButtonHeight;
    [textfield addTarget:self action:@selector(textDidChange) forControlEvents:UIControlEventEditingChanged];

    [textfield becomeFirstResponder];
    /**
     *  监听键盘中删除键的操作
     */
    [textfield setDeleteBackwardblock:^{
        if (weakSelf.tagTextField.hasText) {
            return ;
        }
        NYTagsButton *button = self.tagButtons.lastObject;
        [self delegateTag:button];
        
}];
    textfield.delegate = self;
}

- (void)setupTagButtons
{
    for (NSString *tag in self.tags) {
        self.tagTextField.text = tag;
        [self addTag];
    }
}
//添加标签按钮（懒加载）
- (UIButton *)addTagButton
{
    if (_addTagButton == nil) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundColor:NYTagBgColor];
        [button addTarget:self action:@selector(addTag) forControlEvents:UIControlEventTouchUpInside];
        
        button.width = self.contentView.width;
        button.height = NYtagButtonHeight;
        
        //设置button内部的间距
        button.contentEdgeInsets = UIEdgeInsetsMake(0, SmallMargin, 0, SmallMargin);
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        /**
         *  设置按钮靠左对齐
         */
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [self.contentView addSubview:button];
        _addTagButton = button;
        
    }
    return _addTagButton;
}
- (void)addTag{
    /**
     *  没有文字，不添加标签
     */
    if (self.tagTextField.hasText==NO) return;
    
    if (self.tagButtons.count == 5) {
        [SVProgressHUD showErrorWithStatus:@"最多只能添加5个标签哦" maskType:SVProgressHUDMaskTypeBlack];
        return;
    }
    
    //添加一个标签按钮
    NYTagsButton *tagbutton = [[NYTagsButton alloc]init];
    [tagbutton setTitle:self.tagTextField.text forState:UIControlStateNormal];
    [tagbutton addTarget:self action:@selector(delegateTag:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:tagbutton];
    
    //计算标签按钮的位置
    NYTagsButton *lasttagbutton = self.tagButtons.lastObject;
    
    if (lasttagbutton) {
        //同一行的宽度
        CGFloat rightWidth = self.contentView.width -CGRectGetMaxX(lasttagbutton.frame) - SmallMargin;
        if (rightWidth >= tagbutton.width) {
            tagbutton.y = lasttagbutton.y;
            tagbutton.x = CGRectGetMaxX(lasttagbutton.frame) + SmallMargin;
            
        }else{
            tagbutton.x = 0;
            tagbutton.y = CGRectGetMaxY(lasttagbutton.frame) + SmallMargin;
        }
    }
    [self.tagButtons addObject:tagbutton];
    
    //文字清空
    self.tagTextField.text = nil;
    
    [self setupTextFieldFrame];
    
    //隐藏添加标签
    self.addTagButton.hidden = YES;
}
- (void)delegateTag:(NYTagsButton *)delegateButton
{
    [UIView beginAnimations:nil context:nil];
    NSInteger index = [self.tagButtons indexOfObject:delegateButton];
    
    [delegateButton removeFromSuperview];
    
    [self.tagButtons removeObject:delegateButton];
    /**
     *  重新布局后面的按钮位置
     */
    for (NSInteger i = index; i < self.tagButtons.count; i++) {
        NYTagsButton *tagButton = self.tagButtons[i];
        if (i>0) {
            NYTagsButton *prevoiusTagButton = self.tagButtons[i- 1];
            CGFloat rightWidth = self.contentView.width - CGRectGetMaxX(prevoiusTagButton.frame);
            if (rightWidth>tagButton.width) {
                tagButton.y = prevoiusTagButton.y;
                tagButton.x = CGRectGetMaxX(prevoiusTagButton.frame) + SmallMargin;
                
            } else {
                tagButton.x = 0;
                tagButton.y = CGRectGetMaxY(prevoiusTagButton.frame) + SmallMargin;
            }
        }else{
            tagButton.x = 0;
            tagButton.y = 0;
        }
    }
    [self setupTextFieldFrame];
    [UIView commitAnimations];
}
#pragma mark - 监听
- (void)textDidChange
{
    if (self.tagTextField.hasText) {
        //有文字时，需要设置textframe，保证addtagbutton紧跟
        [self setupTextFieldFrame];
        
        self.addTagButton.hidden = NO;
        [self.addTagButton setTitle:[NSString stringWithFormat:@"添加标签：%@",self.tagTextField.text]  forState:UIControlStateNormal];
        
        //添加按钮，查看最后输入的文字
        NSString*text = self.tagTextField.text ;
        if (text.length == 1) {
            return;
        }
        
        unichar lastChar = [text characterAtIndex:text.length -1];
        
        NSString *lastString = [NSString stringWithFormat:@"%C",lastChar];
        if ([lastString isEqualToString:@","]||[lastString isEqualToString:@"，"]) {
            
            [self.tagTextField deleteBackward];
            [self addTag];
        }
    }else
    {        self.addTagButton.hidden = YES;
    }
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self addTag];
    return YES;
}
#pragma mark - 监听
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


#pragma mark - 设置textfieldframe
- (void)setupTextFieldFrame
{
    NYTagsButton *tagbutton = self.tagButtons.lastObject;
    
    CGFloat textFieldWidth = [self.tagTextField.text sizeWithAttributes:@{NSFontAttributeName :self.tagTextField.font}].width;
    
    textFieldWidth = MAX(100, textFieldWidth);
    
    CGFloat rightWidth = self.contentView.width - CGRectGetMaxX(tagbutton.frame) - SmallMargin;
    if (rightWidth >= textFieldWidth) {
        self.tagTextField.y = tagbutton.y;
        self.tagTextField.x = CGRectGetMaxX(tagbutton.frame) + SmallMargin;
        
    }else
    {
        self.tagTextField.y = CGRectGetMaxY(tagbutton.frame)+ SmallMargin;
        self.tagTextField.x = 0;

    }
    self.addTagButton.y = CGRectGetMaxY(self.tagTextField.frame)+SmallMargin;
}
@end
